from OpenSSL import crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import base64
import json
import requests


def get_public_key(cer_file_path):
    """
    从cer证书中提取公钥
    :param cer_file: cer证书存放的路径
    :return: 公钥
    """
    cert = crypto.load_certificate(crypto.FILETYPE_ASN1, open(cer_file_path, "rb").read())
    res = crypto.dump_publickey(crypto.FILETYPE_PEM, cert.get_pubkey()).decode("utf-8")
    return res.strip()


def get_private_key(pfx_file_path, password="ysyun"):
    """
    从pfx证书中提取私钥,如果证书已加密，需要输入密码
    :param pfx_file_path:pfx证书存放的路径
    :param password:证书密码
    :return:私钥
    """
    pfx = crypto.load_pkcs12(open(pfx_file_path, 'rb').read(), password)
    res = crypto.dump_privatekey(crypto.FILETYPE_PEM, pfx.get_privatekey()).decode("utf-8")
    return res.strip()


def rsa_encrypt(message, res_public):
    """校验RSA加密 使用公钥进行加密"""
    cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(res_public))
    cipher_text = base64.b64encode(cipher.encrypt(message.encode())).decode()
    return cipher_text


def base64_encrypt(rsa_string):
    bytes_str = rsa_string.encode('utf-8')
    b64_str = base64.b64encode(bytes_str)
    return str(b64_str, encoding='utf-8')


def req(b64_string):
    data = {"requestId": "1", "srcMerchantNo": "1", "tradeTime": "1", "version": "1", "charset": "1", "signType": "1",
            "sign": b64_string, "bizContentJson": b64_string}
    # url = "xxxx"
    # rep = requests.post(url, data=data)
    # res = rep.json()
    # return res


res_public = get_public_key(r'C:\Users\Administrator\Desktop\ysyun.cer')
string = {"a": 1}
rsa_string = rsa_encrypt(str(string), res_public)
b64_string = base64_encrypt(rsa_string)
print(b64_string)
req(b64_string)
